package
{
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.Timer;
	
	import classes.RecodeEvent;
	import classes.RecordManager;
	import classes.Waveform;
	
	import fl.containers.ScrollPane;
	import fl.controls.CheckBox;
	
	[SWF( width="600", height="184", frameRate="40" )]
	public class Main extends Sprite
	{
		private var _skin:SpeakingSkin;
		private var _recordManager:RecordManager;
		private var _btnRecordAndStop:MovieClip;
		private var _btnPlay:MovieClip;
		private var _btnYourSnd:Sprite;
		private var _chkShadow:CheckBox;
		private var _textRecording:MovieClip;
		private var _waveContainer:MovieClip;
		private var _scroll:ScrollPane;
		private var _wave:MovieClip;
		private var _nativeWave:Sprite;
		private var _yourWave:Sprite;
		private var _timeLine:Sprite;
		private var _playHead:Sprite;
		private var _userId:String = "";
		private var _nativeSndId:String = "";
		private var _nativeSndUrl:String = "";
		private var _naviveSnd:Sound;
		private var _naviveSndCh:SoundChannel;
		private var _waveform:Waveform;
		private var _playing:Boolean = false;
		private var _playingType:String = "";
		private var _playTimer:Timer;
		private var _dictationSelect:String;
		private var _httpDictationSelect:URLLoader;
		private var _splitStartArray:Array = [];
		private var _splitEndArray:Array = [];
		private var _splitTotalWidth:Number;
		private var _startSec:Number = 0;
		private var _endSec:Number = 0;
		public function Main(){
			init();
			setSkin();
			addEvents();
			loadMark();
		}
		private function init():void{
			_recordManager = new RecordManager();
			_userId = loaderInfo.parameters.userID || "chunk";
			_dictationSelect = loaderInfo.parameters.dictationSelect || "http://www.chunkeng.co.kr/ap_shop/sp_dictation/dictationSelect.php";
			var nativeSndData:String = loaderInfo.parameters.dictationFiles || "224,http://www.chunkeng.co.kr/ap_shop/sp_dictation/songs/TrackNo11.mp3";
			var nativeSndDataArr:Array = nativeSndData.split( "," );
			if( nativeSndDataArr.length != 2 ) return;
			_nativeSndId = nativeSndDataArr[ 0 ];
			_nativeSndUrl = nativeSndDataArr[ 1 ];
			_playTimer = new Timer( 10 );
			_httpDictationSelect = new URLLoader();
		}
		private function setSkin():void{
			_skin = new SpeakingSkin();
			_skin.count.visible = false;
			_btnRecordAndStop = _skin.btnRecordAndPause;
			_btnPlay = _skin.btnPlay;
			_btnYourSnd = _skin.btnYourSnd;
			_chkShadow = _skin.chkShadow as CheckBox;
			_textRecording = _skin.textRecording;
			_textRecording.stop();
			_waveContainer = _skin.waveContainer;
			_wave = _skin.waveContainer.wave;
			_nativeWave = _wave.waveNative;
			_yourWave = _wave.waveYour;
			_timeLine = _wave.timeline;
			_playHead = _wave.playHead;
			_scroll = _waveContainer.scroll as ScrollPane;
			_scroll.setSize( _wave.width, 137 );
			_scroll.source = _wave;
			_waveform = new Waveform( _nativeWave, _yourWave, _timeLine );
			addChild( _skin );
		}
		private function addEvents():void{
			_recordManager.addEventListener( "count", recordCountHandler );
			_recordManager.addEventListener( "start", recordStartHandler );
			_recordManager.addEventListener( "end", recordEndHandler );
			_recordManager.addEventListener( RecodeEvent.PLAYING, recoedSndPlayHandler );
			_btnRecordAndStop.buttonMode = _btnPlay.buttonMode = true;
			_btnRecordAndStop.addEventListener( MouseEvent.CLICK, clickRecordStartHandler);
			_btnPlay.addEventListener( MouseEvent.CLICK, clickPlaytHandler );
			_btnYourSnd.addEventListener( MouseEvent.CLICK, clickYourSndHandler );
			_playTimer.addEventListener( TimerEvent.TIMER, checkNativeSndPosition );
			_httpDictationSelect.addEventListener( Event.COMPLETE, getMarkDataHandler ); 
		}
		private function loadMark():void{
			_httpDictationSelect.load( new URLRequest( _dictationSelect + "?userID="+_userId +"&fileID="+_nativeSndId ))
		}
		private function loadSound( url:String ):void{
			_naviveSnd = new Sound();	
			_naviveSnd.addEventListener(Event.COMPLETE, soundFileCompleteHandler );
			var soundTrans:SoundTransform = new SoundTransform();
			soundTrans.volume = 0.3;
			if( url.indexOf( "songs/" ) == -1  ) url = "songs/"+url;
			_naviveSnd.load(new URLRequest( url ) );
			
		}
		private function playNativeSnd():void{
			_btnPlay.gotoAndStop( 2 );
			_naviveSndCh = _naviveSnd.play( _startSec*1000 );
			_wave.setChildIndex( _yourWave, 0 );
			_playTimer.start()
		}
		private function stopNativeSnd():void{
			_btnPlay.gotoAndStop( 1 );	
			if( _naviveSndCh ) _naviveSndCh.stop();
			_playTimer.stop();
		}
		private function checkNativeSndPosition( event:TimerEvent ):void{
			var startMilSec:Number = (_startSec*1000)
			var endMilSec:Number = (_endSec*1000)
			_playHead.x = ( 0-_waveform.naitveMaxWidth)/( startMilSec - endMilSec )*( _naviveSndCh.position-startMilSec );
			if( _naviveSndCh.position >= _endSec*1000 ){
				_naviveSndCh.stop();
				if( _naviveSndCh ) _naviveSndCh.stop();
				if( _chkShadow.selected ) clickYourSndHandler( null );
			}
		}
		private function soundFileCompleteHandler( event:Event ):void{
			var sndLength:Number = _naviveSnd.length / 1000;
			var sndBytes:Number = ( _naviveSnd.length/1000) *44100
			var startPos:Number = ( sndBytes-0 ) / ( _splitTotalWidth-0 ) * ( _splitStartArray[ 0 ]);
			var endPos:Number = ( sndBytes-0 ) / ( _splitTotalWidth-0 ) * ( _splitEndArray[ 0 ]);
			_startSec = ( sndLength-0 ) / ( _splitTotalWidth-0 ) * ( _splitStartArray[ 0 ]);
			_endSec = ( sndLength-0 ) / ( _splitTotalWidth-0 ) * ( _splitEndArray[ 0 ]);
			_waveform.drawNative( _naviveSnd, startPos, endPos-startPos );
			//trace( _splitTotalWidth + " / " + _splitStartArray[ 0 ] + " / " + _splitEndArray[ 0 ]);
			//trace( sndBytes + " / " + startPos + " / " + endPos );
			//trace( sndLength + " / " + _startSec + " / " + _endSec );
			_waveform.drawtimeLine( _startSec, _startSec );
			_scroll.refreshPane();
		}
		private function clickRecordStartHandler( evnet:MouseEvent ):void{
			if( _recordManager.recording ){
				_skin.btnRecordAndPause.gotoAndStop(1);
				_recordManager.end();
				_textRecording.gotoAndStop(1);
			}else{
				_skin.btnRecordAndPause.gotoAndStop(2);
				_waveform.clearYour();
				_recordManager.start();	
				_skin.count.visible = true;
				stopNativeSnd();
			}
		}
		private function clickPlaytHandler( evnet:MouseEvent ):void{
			if( !_naviveSnd ) return;
			if( _naviveSndCh ) _naviveSndCh.stop();
			_playing = !_playing;
			if( _playing ) {
				playNativeSnd();
				_nativeWave.alpha = 1;
				_yourWave.alpha = 0.2;
			}else{
				stopNativeSnd();
			}
		}
		private function clickYourSndHandler( evnet:MouseEvent ):void{
			_wave.setChildIndex( _nativeWave, 0 );
			_nativeWave.alpha = 0.2;
			_yourWave.alpha = 1;
			_recordManager.play();
			_playing = false;
			stopNativeSnd();
		} 
		private function recordCountHandler( event:Event ):void{
			_skin.count.gotoAndStop( _recordManager.count );
		}
		private function recordStartHandler( event:Event ):void{
			_skin.count.visible = false;
			_textRecording.gotoAndPlay(1);
		}
		private function recordEndHandler( event:Event ):void{
			_waveform.drawYour( _recordManager.src );
			_yourWave.alpha = 1;
		}
		private function recoedSndPlayHandler( event:RecodeEvent ):void{
			_playHead.x = ( 0-_waveform.yourMaxWidth)/( 0 - event.totalByteLength )*( event.playedByteLength );
		}
		private function getMarkDataHandler( event:Event ):void{
			var selectResult:String = event.target.data.toString();
			var sValue:Array = selectResult.split(",");
			_splitTotalWidth = Number( sValue[ 0 ] );
			for(var i:int; i<sValue.length-1; i++){
				if(i > 1) {
					_splitStartArray.push(sValue[i]);
					_splitEndArray.push(sValue[i+1]);
				}
				i++;
			}     
			loadSound( _nativeSndUrl );
		}
	}
}